/**
 * Copyright (C) 2009+ Spark Zheng
 *
 * @file        src/dlloader.c 
 * @date        2010-01-11
 * @brief
 * @see         dlib
 * @history
 */

#include <string.h>
#include "dlloader.h"
#include "mempool.h"

dlib_dlloader_t *dlib_dlloader_init(const char *soname, int flag)
{
	void *handler = NULL;
	dlib_dlloader_t *loader = NULL;
	if (soname == NULL) {
		return NULL;
	}

	handler = dlopen(soname, RTLD_LAZY | flag);
	if (handler == NULL) {
		return NULL;
	}

	loader = dmalloc_nb(sizeof(*loader));
	if (loader == NULL) {
		dlclose(loader->handler);
		return NULL;
	}
	loader->handler = handler;
	strncpy(loader->soname, soname, PATH_MAX);

	return loader;
}

void *dlib_dlloader_symbol(dlib_dlloader_t *loader, const char *sym)
{
	if (loader == NULL || loader->handler == NULL || sym == NULL) {
		return NULL;
	}
	return dlsym(loader->handler, sym);
}

void dlib_dlloader_exit(dlib_dlloader_t *loader)
{
	if (loader == NULL || loader->handler == NULL) {
		return;
	}
	dlclose(loader->handler);
	return;
}

